import React, { useState, useEffect, useRef } from 'react'
import * as echarts from 'echarts';
import { getList } from '../../api/index'
import './echarts.scss'
export default function Echarts() {

  const chartRef = useRef();
  const chartRef1 = useRef();

  const [data, setdata] = useState([])

  function getData() {
    getList('getEcharts').then((res) => {
      setdata(res.data.list)
      lineEchar(res.data.list)
      pieEchar(res.data.list)
    })
  }

  const lineEchar = (data) => {
    let newdata = [...data.map(item => item.sales)]
    const chartInstance = echarts.init(chartRef.current);
    const options = {
      title: { text: '销售量' },
      tooltip: { trigger: 'axis', axisPointer: { type: 'cross', crossStyle: { color: '#999' } } },
      xAxis: { type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周天'] },
      yAxis: { type: 'value' },
      series: [{ name: '销量', type: 'line', data: newdata }]
    };
    return options && chartInstance.setOption(options);
  }

  const pieEchar = (data) => {
    const myChart = echarts.init(chartRef1.current);
    
    let newdata= []
    data.forEach((item,i)=>{
      let obj={
        value:item.turnover,
        name:item.day
      }
      newdata.push(obj)
    })
    const option = {
      title: { text: '营业额', subtext: 'day Data', left: 'left' },
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'right' },
      series: [{
        name: '业额', type: 'pie', radius: '50%', data: newdata,
        emphasis: {itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }}
      }
      ]
    };

    return option && myChart.setOption(option);
  }





  useEffect(() => {
    getData()
  }, []);

  return (
    <div id='echartsWrap'>
      <div ref={chartRef} style={{ width: '550px', height: "400px" }}></div>
      <div ref={chartRef1} style={{ width: '550px', height: "400px" }}></div>
    </div>
  );

}
